package com.gcloud.mesh.monitor.dao;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.gcloud.framework.db.dao.impl.JdbcBaseDaoImpl;
import com.gcloud.mesh.monitor.entity.StatisticsEntity;

@Repository
public class StatisticsDao extends JdbcBaseDaoImpl<StatisticsEntity, String> {

	public StatisticsEntity getLastData(String meter, String resourceId) {
		List<Object> values = new ArrayList<>();
		values.add(meter);
		values.add(resourceId);
		List<StatisticsEntity> points = this.findBySql(
				"SELECT s.`value`,s.timestamp FROM dcs_statistics_data s WHERE s.meter = ? and s.resource_id = ? order by timestamp desc limit 1",
				values);
		if (points != null && points.size() > 0) {
			return points.get(0);
		}
		return null;
	}

	public List<StatisticsEntity> getData(String meter, String resourceId) {
		List<Object> values = new ArrayList<>();
		values.add(meter);
		values.add(resourceId);
		List<StatisticsEntity> points = this.findBySql(
				"SELECT s.* FROM dcs_statistics_data s WHERE s.meter = ? and s.resource_id = ? order by timestamp desc limit 60",
				values, StatisticsEntity.class);
		return points;
	}

	public void deleteByTime(Date beforeDate) {
		StringBuilder sb = new StringBuilder();
		sb.append("DELETE FROM dcs_statistics_data WHERE timestamp < '" + this.convertDateToString(beforeDate) + "' ");
		this.jdbcTemplate.execute(sb.toString());
	}

	private String convertDateToString(Date date) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return dateFormat.format(date);
	}
}
